import React, { useEffect, useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-table';
import { ProColumns } from '@ant-design/pro-table';
import {
  addRole,
  deleteRole,
  getFormatRole,
  listRole,
  updateRole,
} from './api';
import { handleRemove } from '@/utils/actions';
import MegaCreateForm from '@/compoments/MegaCreateForm';
import MegaUpdateForm from '@/compoments/MegaUpdateForm';
import MegaTable from '@/compoments/MegaTable';
import { RoleEntity } from './entities';
import { formChildren } from './form';
import { getFormatTenant, getTenantOptions } from '../Tenant/api';
import { Spin } from 'antd';
import { TenantEntityFormat } from '../Tenant/entities';

export default () => {
  const tableActionRef = useRef<ActionType>();

  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [currentEntity, setCurrentEntity] = useState<RoleEntity>();

  const [tenantOptions, setTenantOptions] = useState<OptionEntity[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [tenantId, setTenantId] = useState<string>();
  const [tenant, setTenant] = useState<TenantEntityFormat>();

  const transform = (value: any) => {
    const { allow_nodes } = value;
    return {
      ...value,
      allow_nodes: allow_nodes.join(','),
    }
  }

  async function initTenantOptions() {
    try {
      const options = await getTenantOptions();
      if (options[0]) {
        setTenantId(options[0].value as string)
      }
      setTenantOptions(options);
    } catch (error) {

    } finally {
      setLoading(false);
    }
  }

  const initTenant = async (id: string) => {
    const newTenant = await getFormatTenant(id);
    setTenant(newTenant)
  }

  useEffect(() => {
    initTenantOptions();
  }, []);

  useEffect(() => {
    if (tenantId) {
      initTenant(tenantId);
    }
  }, [tenantId]);

  if (loading) return <Spin spinning={true} />

  const tableColumns: ProColumns<RoleEntity>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '节点',
      dataIndex: 'allow_nodes',
      hideInSearch: true,
    },
    {
      title: '最大CPU(核)',
      dataIndex: 'max_cpu',
      hideInSearch: true,
    },
    {
      title: '最大内存(G)',
      dataIndex: 'max_memory',
      hideInSearch: true,
    },
    {
      title: '最大硬盘(G)',
      dataIndex: 'max_disk',
      hideInSearch: true,
    },
    {
      title: '租户',
      dataIndex: 'tenant_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: false,
        options: tenantOptions,
        onChange: (value: string) => setTenantId(value)
      },
      initialValue: tenantId
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentEntity(record);
            handleUpdateModalVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await handleRemove(record.id, deleteRole);
            tableActionRef.current?.reloadAndRest?.();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <div style={{ paddingTop: 16 }}>
      <MegaTable
        handleCreateModalVisible={handleCreateModalVisible}
        columns={tableColumns}
        actionRef={tableActionRef}
        title={'角色'}
        tableRequest={tenantId ? listRole : undefined}
        deleteRowAction={deleteRole}
      />
      {
        tenant && (
          <>
            <MegaCreateForm
              handleModalVisible={handleCreateModalVisible}
              actionRef={tableActionRef}
              modalVisible={createModalVisible}
              title={'新增角色'}
              addEntityAction={(data: any) => addRole({ ...data, tenant_id: tenantId })}
              transform={transform}
            >
              {formChildren(tenant)}
            </MegaCreateForm>

            <MegaUpdateForm
              handleModalVisible={handleUpdateModalVisible}
              actionRef={tableActionRef}
              modalVisible={updateModalVisible}
              currentEntity={currentEntity}
              title={'编辑角色'}
              getEntityAction={getFormatRole}
              updateEntityAction={updateRole}
              transform={transform}
            >
              {formChildren(tenant)}
            </MegaUpdateForm>
          </>
        )
      }
    </div>
  );
}
